/*
 * Copyright 2002-2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package my.convert.attribute.processor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;


public class CustomDateEditor extends PropertyEditorSupport {
    public Logger logger = LoggerFactory.getLogger(getClass());

    public static final SimpleDateFormat datetime_df_1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    public static final SimpleDateFormat datetime_df_2 = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
    public static final SimpleDateFormat datetime_df_3 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    public static final SimpleDateFormat datetime_df_4 = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
    public static final SimpleDateFormat datetime_df_7 = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
    public static final SimpleDateFormat datetime_df_5 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    public static final SimpleDateFormat datetime_df_6 = new SimpleDateFormat("yyyy/MM/dd HH:mm");
    public static final SimpleDateFormat date_df_1 = new SimpleDateFormat("yyyy-MM-dd");
    public static final SimpleDateFormat date_df_2 = new SimpleDateFormat("dd-MM-yyyy");
    public static final SimpleDateFormat date_df_3 = new SimpleDateFormat("dd/MM/yyyy");
    public static final SimpleDateFormat date_df_4 = new SimpleDateFormat("yyyy/MM/dd");
    public static final SimpleDateFormat time_df_1 = new SimpleDateFormat("HH:mm:ss");
    public static final SimpleDateFormat time_df_2 = new SimpleDateFormat("HH:mm");
    private static Object[][] patterns = {
            {Pattern.compile("^\\d{4}-\\d{2}-\\d{2}$"), date_df_1},
            {Pattern.compile("^\\d{2}-\\d{2}-\\d{4}$"), date_df_2},
            {Pattern.compile("^\\d{2}/\\d{2}/\\d{4}$"), date_df_3},
            {Pattern.compile("^\\d{4}/\\d{2}/\\d{2}$"), date_df_4},
            {Pattern.compile("^\\d{4}-\\d{2}-\\d{2} \\d+:\\d+$"), datetime_df_5},
            {Pattern.compile("^\\d{4}/\\d{2}/\\d{2} \\d+:\\d+$"), datetime_df_6},
            {Pattern.compile("^\\d{4}-\\d{2}-\\d{2} \\d+:\\d+:\\d+$"), datetime_df_1},
            {Pattern.compile("^\\d{4}/\\d{2}/\\d{2} \\d+:\\d+:\\d+$"), datetime_df_3},
            {Pattern.compile("^\\d{2}-\\d{2}-\\d{4} \\d+:\\d+:\\d+$"), datetime_df_4},
            {Pattern.compile("^\\d{2}/\\d{2}/\\d{4} \\d+:\\d+:\\d+$"), datetime_df_7},
            {Pattern.compile("^\\d{8} \\d+:\\d+:\\d+$"), datetime_df_2},
            {Pattern.compile("^\\d+:\\d+:\\d+$"), time_df_1},
            {Pattern.compile("^\\d+:\\d+$"), time_df_2}
    };
    private boolean allowEmpty = false;

    public CustomDateEditor(boolean allowEmpty) {
        this.allowEmpty = allowEmpty;

    }

    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        String input = (text != null ? text.trim() : null);
        if (this.allowEmpty && (input == null || "".equals(input))) {
            // Treat empty String as null value.
            setValue(null);
            return;//当text 为null 或 "" 时，返回空日期对象
        }
        Date obj = null;
        SimpleDateFormat df = null;
        for (Object[] item : patterns) {
            Pattern p = (Pattern) item[0];
            if (p.matcher(input).matches()) {
                df = (SimpleDateFormat) item[1];
                break;
            }
        }
        try {
            if (df != null) {
                df = new SimpleDateFormat(df.toPattern());//因为SimpleDateFormat是线程不安全的，因此，重创建一个SimpleDateFormat
                obj = df.parse(input);
                logger.debug(df.toPattern() + ">> 日期格式转换成功");
            }
        } catch (ParseException e) {
            //logger.debug(df.toString()+">> 日期格式匹配失败");
        }

        if (obj != null) {
            setValue(obj);
        } else {
            throw new IllegalArgumentException("Invalid date value [" + text + "]");
        }
    }

    @Override
    public String getAsText() {
        if (getValue() != null) {
            return datetime_df_1.format(getValue());
        } else {
            return "";
        }
    }

}
